export class MyURLSearchParams {
  constructor(init) {
    this.params = new Map();

    if (init) {
      if (typeof init === 'string') {
        this.parseQueryString(init);
      } else if (init instanceof MyURLSearchParams) {
        this.params = new Map(init.params);
      } else if (typeof init === 'object') {
        for (const key in init) {
          if (init.hasOwnProperty(key)) {
            this.append(key, init[key]);
          }
        }
      }
    }
  }

  parseQueryString(queryString) {
    // 移除开头的 '?'，然后拆分成键值对
    queryString = queryString.startsWith('?') ? queryString.slice(1) : queryString;
    const pairs = queryString.split('&');

    for (const pair of pairs) {
      const [key, value] = pair.split('=').map(decodeURIComponent);
      this.append(key, value);
    }
  }

  append(name, value) {
    if (this.params.has(name)) {
      this.params.get(name).push(value);
    } else {
      this.params.set(name, [value]);
    }
  }

  get(name) {
    return this.params.has(name) ? this.params.get(name)[0] : null;
  }

  getAll(name) {
    return this.params.has(name) ? this.params.get(name) : [];
  }

  has(name) {
    return this.params.has(name);
  }

  delete(name) {
    this.params.delete(name);
  }
  sort() {
    const sortedParams = new Map([...this.params.entries()].sort((a, b) => a[0].localeCompare(b[0])));
    this.params = sortedParams;
  }

  toString() {
    const queryString = [];
    for (const [key, values] of this.params.entries()) {
      for (const value of values) {
        queryString.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
      }
    }
    return queryString.join('&');
  }
}